package com.game.xmldata;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.game.utils.XmlParserKit;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Getter
public abstract class AbstractSampleFactory<T> {
	protected Map<Integer, T> map = new HashMap<>();
	protected List<T> list = new ArrayList<>();

	public void init() {
	};// 子类具体实现

	public abstract String getFileName();

	public abstract Class<T> getClazz();

	public void load(String xmldataConfig) {
		map.clear();
		list.clear();
		File file = new File(xmldataConfig + File.separator + getFileName());
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(file);
			Element root = document.getRootElement();
			List<Element> elements = root.elements();
			Class<T> clazz = getClazz();
			for (Element e : elements) {
				T sample = null;
				sample = clazz.newInstance();
				int sid = 0;
				for (Field field : clazz.getDeclaredFields()) {
					String fieldName = field.getName();
					Object value = e.attributeValue(fieldName);
					if (value != null) {
						field.setAccessible(true);
						field.set(sample, XmlParserKit.convertType(field.getType(), value));
						if (fieldName.equalsIgnoreCase("sid")) {
							sid = field.getInt(sample);
						}
					}
				}
				if (sid > 0) {
					map.put(sid, sample);
					list.add(sample);
				} else {
					log.error("sid <=0   clazzName:" + clazz.getName());
				}
			}
			init();
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}
}
